// StandardDetailSearchServlet.java
package com.medical.standard.controller.search;

import entity.StandardDetail;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/standardDetailSearch")
public class StandardDetailSearchServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        String standardId = request.getParameter("standardId");
        String keyword = request.getParameter("keyword");

        if (standardId == null || standardId.trim().isEmpty()) {
            response.getWriter().write("{\"success\":false,\"message\":\"标准ID不能为空\"}");
            return;
        }

        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            List<StandardDetail> detailList = new ArrayList<>();

            // 1. 从term表检索
            String termSql = "SELECT project_num, term_name, definition FROM term " +
                    "WHERE standard_id = ? AND (term_name LIKE ? OR definition LIKE ?)";
            pstmt = conn.prepareStatement(termSql);
            pstmt.setInt(1, Integer.parseInt(standardId));
            pstmt.setString(2, "%" + keyword + "%");
            pstmt.setString(3, "%" + keyword + "%");

            rs = pstmt.executeQuery();
            while (rs.next()) {
                StandardDetail detail = new StandardDetail(
                        rs.getString("project_num"),
                        rs.getString("term_name"),
                        rs.getString("definition"),
                        "term"
                );
                detailList.add(detail);
            }
            rs.close();
            pstmt.close();

            // 2. 从inspection表检索
            String inspectionSql = "SELECT project_num, project_name, project_requirement FROM inspection " +
                    "WHERE standard_id = ? AND (project_name LIKE ? OR project_requirement LIKE ?)";
            pstmt = conn.prepareStatement(inspectionSql);
            pstmt.setInt(1, Integer.parseInt(standardId));
            pstmt.setString(2, "%" + keyword + "%");
            pstmt.setString(3, "%" + keyword + "%");

            rs = pstmt.executeQuery();
            while (rs.next()) {
                StandardDetail detail = new StandardDetail(
                        rs.getString("project_num"),
                        rs.getString("project_name"),
                        rs.getString("project_requirement"),
                        "inspection"
                );
                detailList.add(detail);
            }
            rs.close();
            pstmt.close();

            // 3. 从requirement表检索
            String requirementSql = "SELECT project_num, project_name, project_requirement FROM requirement " +
                    "WHERE standard_id = ? AND (project_name LIKE ? OR project_requirement LIKE ?)";
            pstmt = conn.prepareStatement(requirementSql);
            pstmt.setInt(1, Integer.parseInt(standardId));
            pstmt.setString(2, "%" + keyword + "%");
            pstmt.setString(3, "%" + keyword + "%");

            rs = pstmt.executeQuery();
            while (rs.next()) {
                StandardDetail detail = new StandardDetail(
                        rs.getString("project_num"),
                        rs.getString("project_name"),
                        rs.getString("project_requirement"),
                        "requirement"
                );
                detailList.add(detail);
            }

            // 将结果转换为JSON格式返回
            StringBuilder json = new StringBuilder();
            json.append("{\"success\":true,\"data\":[");
            for (int i = 0; i < detailList.size(); i++) {
                StandardDetail detail = detailList.get(i);
                json.append("{");
                json.append("\"projectNum\":\"").append(escapeJson(detail.getProjectNum())).append("\",");
                json.append("\"projectName\":\"").append(escapeJson(detail.getProjectName())).append("\",");
                json.append("\"projectRequirement\":\"").append(escapeJson(detail.getProjectRequirement())).append("\",");
                json.append("\"tableType\":\"").append(escapeJson(detail.getTableType())).append("\"");
                json.append("}");
                if (i < detailList.size() - 1) {
                    json.append(",");
                }
            }
            json.append("]}");

            response.getWriter().write(json.toString());

        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"检索失败\"}");
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }
    }

    private String escapeJson(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}